package club.menglinking.wechat.util;

import club.menglinking.wechat.entity.AesException;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * @ClassName WeChatUtil
 * @Author Administrator
 * @Date 2018/12/30 13:25
 * @Version 1.0
 * @Description
 **/
public class WeChatUtil {

    private static WeChatUtil weChatUtil=null;

    private WeChatUtil(){}

    public static WeChatUtil getWeChatUtil(){
        if (weChatUtil==null){
            weChatUtil=new WeChatUtil();
        }
        return weChatUtil;
    }
    public String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
    {
        try {
            String[] array = new String[] { token, timestamp, nonce, encrypt };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }

}
